﻿/// <reference path="adapter/ext/ext-base-debug.js" />

/// <reference path="ext-all-debug-w-comments.js" />
Ext.util.TaskRunner = function (interval) {
    interval = interval || 10;
    var tasks = [],
    	removeQueue = [],
    	id = 0,
    	running = false,

    	// private
    	stopThread = function () {
    	    running = false;
    	    clearInterval(id);
    	    id = 0;
    	},

    	// private
    	startThread = function () {
    	    if (!running) {
    	        running = true;
    	        id = setInterval(runTasks, interval);
    	    }
    	},

    	// private
    	removeTask = function (t) {
    	    removeQueue.push(t);
    	    if (t.onStop) {
    	        t.onStop.apply(t.scope || t);
    	    }
    	},

    	// private
    	runTasks = function () {
    	    var rqLen = removeQueue.length,
	    		now = new Date().getTime();

    	    if (rqLen > 0) {
    	        for (var i = 0; i < rqLen; i++) {
    	            tasks.remove(removeQueue[i]);
    	        }
    	        removeQueue = [];
    	        if (tasks.length < 1) {
    	            stopThread();
    	            return;
    	        }
    	    }
    	    for (var i = 0, t, itime, rt, len = tasks.length; i < len; ++i) {
    	        t = tasks[i];
    	        itime = now - t.taskRunTime;
    	        if (t.interval <= itime) {
    	            rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
    	            t.taskRunTime = now;
    	            if (rt === false || t.taskRunCount === t.repeat) {
    	                removeTask(t);
    	                return;
    	            }
    	        }
    	        if (t.duration && t.duration <= (now - t.taskStartTime)) {
    	            removeTask(t);
    	        }
    	    }
    	};

    this.start = function (task) {
        tasks.push(task);
        task.taskStartTime = new Date().getTime();
        task.taskRunTime = 0;
        task.taskRunCount = 0;
        startThread();
        return task;
    };

  
    this.stop = function (task) {
        removeTask(task);
        return task;
    };

 
    this.stopAll = function () {
        stopThread();
        for (var i = 0, len = tasks.length; i < len; i++) {
            if (tasks[i].onStop) {
                tasks[i].onStop();
            }
        }
        tasks = [];
        removeQueue = [];
    };

    this.hasRunning = function () { return tasks.length > 0 }
};


var maps, playForm, lTPoints_I = 0, zoom = 3, interval = 2000, stepLength = 1, quickness = 2, isPlay = true, playBtn, playRate=1,runFn;



var runner = new Ext.util.TaskRunner();


//{ text: '快退', handler: quickBack },
//{ text: '播放', handler: PlayFn },
//{ text: '停止', handler: playStop },
//{ text: '快进', handler: quickPlay }

function updateStepLength() {

    stepLength = parseInt( playForm.get('stepLength').getValue())
}


function updatePlayRate(v) {
    playRate = parseInt(v, 10)

    if (!runner.hasRunning()) return;
    playForm.get('ivalue2').setValue(v)
    try{
      
        if (playRate) {
            runner.stopAll();
            if (runFn == lTPoints_IAdd) {
                runner.start({
                    run: runFn,
                    interval: interval / playRate
                });
            } else
                runner.start({
                    run: runFn,
                    interval: interval / playRate / quickness
                });
        }else
            playRate = 1;
    } catch (e) {

        dump(e)
    }
}
function playStop() {
    runner.stopAll();
    lTPoints_I = 0
}

function quickBack() {
    runFn = lTPoints_ISub
    runner.stopAll();
    runner.start({
        run: runFn,
        interval:parseInt( interval / playRate / quickness)
    });

}
function quickPlay() {
    var tinterval = parseInt(interval / playRate / quickness)
    
    runFn = lTPoints_IAdd
    runner.stopAll();
    runner.start({
        run: runFn,
        interval: tinterval//parseInt(interval / playRate / quickness)
    });

}
function lTPoints_IAdd() {
 
    if (lTPoints_I >= lTPoints.length) {
        runner.stopAll()
        alert('已经到达终点');
        lTPoints_I = lTPoints.length - 1;
        maps.moveToCenter(lTPoints[lTPoints_I], zoom);
        return;
    }
    playForm.get('playProgress').setValue(lTPoints_I)
    maps.moveToCenter(lTPoints[lTPoints_I], zoom);
    lTPoints_I += stepLength
    
}
function lTPoints_ISub() {
  
        if (lTPoints_I < 0) {
            runner.stopAll()
            alert('已经到达出发点');
            lTPoints_I = 0;
            maps.moveToCenter(lTPoints[lTPoints_I], zoom);
            return;
        }
        playForm.get('playProgress').setValue(lTPoints_I)
        maps.moveToCenter(lTPoints[lTPoints_I], zoom);
        lTPoints_I -= stepLength
   
    }

function lTPointsPlayer() {
    playForm.get('ivalue').setValue(lTPoints_I)
      
        if (lTPoints_I >= lTPoints.length) {
            runner.stopAll()
            alert('已经到达终点');
            lTPoints_I = lTPoints.length - 1;
            maps.moveToCenter(lTPoints[lTPoints_I], zoom);
            return;
        }
        playForm.get('playProgress').setValue(lTPoints_I)
        maps.moveToCenter(lTPoints[lTPoints_I], zoom);
        lTPoints_I += stepLength
    }
function dragplay(v) {
    lTPoints_I = parseInt(v);

    maps.moveToCenter(lTPoints[lTPoints_I], zoom);

}
function PlayFn() {
    runFn = lTPointsPlayer
    if (isPlay) {
        var tinterval = parseInt(interval / playRate )
      
        isPlay = false;
        runner.start({
            run: runFn,
            interval: tinterval
        });
        playBtn.setText('Pause');
    } else {
        isPlay = true;
        runner.stopAll();
        playBtn.setText('Play');
    }
  }

    Ext.onReady(function () {
        playBtn = new Ext.Button({ text: '播放', handler: PlayFn })

        runFn = lTPointsPlayer;

        maps = new LTMaps("myMap");
        maps.centerAndZoom(new LTPoint(10444800, 3514368), 13);	//定位全国
        var standMapControl = new LTStandMapControl();
        maps.addControl(standMapControl);
        maps.handleMouseScroll(true);//启用鼠标滚轮功能支持,参数true代表使用鼠标指向点位置不变模式
        control = new LTPolyLineControl();//增加测距控件
        control.setTips("双击结束");//改变操作提示文字内容
        LTEvent.bind(maps, "dblclick", control, control.endDraw);//在双击地图的时候调用结束操作
        maps.addControl(control);
        controlm = new LTPolygonControl();
        controlm.setTips("双击结束");//改变操作提示文字内容
        LTEvent.bind(maps, "dblclick", controlm, controlm.endDraw);//在双击地图的时候调用结束操作
        maps.addControl(controlm);
        control.setVisible(false);
        controlm.setVisible(false);

        new Ext.Viewport({
            layout: 'border',
            items: [
                   playForm=new Ext.FormPanel({
                       region: 'west',
                       frame: true,
                       labelAlign: 'right',
                       labelWidth: 55,
                       width: 240,//addLTLineOverlay
                       buttons: [{ xtype: 'button', text: 'addMark', handler: function () { addMarkermap(maps) } },
                           { xtype: 'button', text: 'addLTLineOverlay', handler: function () { addLTLineOverlay(maps) } }],
                       waitMsgTarget: true,
                       items: [
                                /* {   xtype : "fieldset",  
                                     title:'',
                                     autoWidth: true,
                                     autoHeight: true,
                                           
                                     items : [*/new Ext.form.RadioGroup(
                                       {
                                           itemId:'',
                                           fieldLabel: '视野',
                                           //    width:180,
                                           items: [
                                                new Ext.form.Radio({            //以上相同
                                                    boxLabel: "锁定",
                                                    name: "borrow",
                                                    inputValue: "lock"

                                                }), new Ext.form.Radio({
                                                    boxLabel: "自由",
                                                    name: "borrow",
                                                    checked: true,
                                                    inputValue: "free"

                                                })
                                           ]
                                       }),
                                         new Ext.form.ComboBox({
                                             id: 'stepLength',
                                             fieldLabel: '回放间隔',
                                             typeAhead: true,
                                             triggerAction: 'all',
                                             lazyRender: false,
                                             mode: 'local',
                                             width: 130,
                                             value: '1',
                                             store: new Ext.data.ArrayStore({
                                                 id: 0,
                                                 fields: [
                                                     'myId',
                                                     'displayText'
                                                 ],
                                                 data: [[1, 'X 1'], [2, 'X 2'], [3, 'X 3'], [4, 'X 4']]
                                             }),
                                             listeners: {
                                            
                                                 select: updateStepLength
                                             },
                                             valueField: 'myId',
                                             displayField: 'displayText'

                                         }),
                                         new Ext.form.SliderField({
                                             id: 'playRate',
                                             fieldLabel: '回放速度',
                                             width: 140,
                                             value: 0,
                                             increment: 1,
                                             minValue: 1,
                                             maxValue: 4,
                                           
                                             markInvalid: function (msg) {
                                                 var field=this
                                                 field.el.addClass(field.invalidClass);
                                                 if (!field.errorIcon) {
                                                     var elp = field.getErrorCt();
                                                     // field has no container el
                                                     if (!elp) {
                                                         field.el.dom.title = msg;
                                                         return;
                                                     }
                                                     field.errorIcon = elp.createChild({ tag: 'div', style: 'text-align:center;width:22px;padding-top:4px; background-color:#e9f2ff;border:#8eaace  solid 1px;', html: msg });
                                                    
                                                     if (field.ownerCt) {
                                                         field.ownerCt.on('afterlayout', field.alignErrorIcon, field);
                                                         field.ownerCt.on('expand', field.alignErrorIcon, field);
                                                     }
                                                     field.on('resize', field.alignErrorIcon, field);
                                                     field.on('destroy', function () {
                                                         Ext.destroy(this.errorIcon);
                                                     }, field);
                                                 }
                                                 field.alignErrorIcon();
                                                 field.errorIcon.dom.qtip = field.getValue();;
                                                 field.errorIcon.dom.innerHTML = field.getValue();
                                            
                                                 field.errorIcon.show();
                                          
                                             },
                                             getErrors: function (v) {
                                                 return [v];
                                             },
                                          
                                             listeners: {
                                                 afterrender: function (tslider) {
                                                     tslider.slider.on('change', function (ts,v) {
                                                         tslider.markInvalid();
                                                         updatePlayRate(v);
                                                     })
                                                 }
                                             }
                                         }),
                                         new Ext.form.SliderField({
                                             fieldLabel: '回放进度',
                                             width: 140,
                                             value: 0,
                                             increment: 1,
                                             minValue: 0,
                                             //maxValue: 1000,
                                             id: 'playProgress',
                                             markInvalid: function (msg) {
                                                 var field = this
                                                 field.el.addClass(field.invalidClass);
                                                 if (!field.errorIcon) {
                                                     var elp = field.getErrorCt();
                                                    
                                                     if (!elp) {
                                                         field.el.dom.title = msg;
                                                         return;
                                                     }
                                                     field.errorIcon = elp.createChild({ tag: 'div', style: 'text-align:center;width:22px;padding-top:4px; background-color:#e9f2ff;border:#8eaace  solid 1px;', html: msg });

                                                     if (field.ownerCt) {
                                                         field.ownerCt.on('afterlayout', field.alignErrorIcon, field);
                                                         field.ownerCt.on('expand', field.alignErrorIcon, field);
                                                     }
                                                     field.on('resize', field.alignErrorIcon, field);
                                                     field.on('destroy', function () {
                                                         Ext.destroy(this.errorIcon);
                                                     }, field);
                                                 }
                                                 field.alignErrorIcon();
                                                 field.errorIcon.dom.qtip = field.getValue();
                                                 field.errorIcon.dom.innerHTML = field.getValue();
                                               
                                                 field.errorIcon.show();

                                             },
                                             getErrors: function (v) {
                                                 return [v];
                                             },
                                           
                                             listeners: {
                                                 afterrender: function (tslider) {
                                                     tslider.slider.on('change', function (ts, v) {
                                                         tslider.markInvalid();
                                                         playForm.get('playProgress').setMaxValue(pointDatas.length - 1);
                                                         dragplay(v)
                                                     })
                                                 }
                                             }
                                         }),
                                          {
                                              xtype: "fieldset",
                                              title: '',
                                              layout: 'column',
                                             
                                              autoHeight: true,
                                              defaultType: 'button',
                                              items: [{ text: '快退', handler: quickBack },
                                                      playBtn,
                                                      { text: '停止', handler: playStop },
                                                      { text: '快进', handler: quickPlay }
                                                     
                                              ]
                                          }, {

                                              id: 'ivalue',
                                              xtype: 'textfield'
                                          }, {

                                              id: 'ivalue2',
                                              xtype: 'textfield'
                                          }

                                     //]}
                       ]


                   }), {
                       region: 'center',
                       xtype: 'panel',
                       title: '地图',
                       tbar: [
                           { text: '放大', handler: function () { maps.zoomIn(); } },
                           { text: '缩小', handler: function () { maps.zoomOut() } },
                           { text: '测距', handler: function () { control.btnClick(); } },
                           { text: '测面', handler: function () { controlm.btnClick(); } },
                           { text: '打印', handler: function () { printMap(maps) } },
                           { text: '清空地图', handler: function () { maps.clearOverLays(); } }
                       ],

                       listeners: { "bodyresize": function () { if (typeof (maps) == "object") { maps.resizeMapDiv(); } } },//监控地图大小改变后,地图自适应
                       contentEl: 'myMap'

                   }
            ]
        })
    });


    function dump(o) {
        var msg = "";
        for (ov in o) {
            msg += "\no[" + ov + "]" + o[ov];
        }
        alert(msg);
        return msg;
    }
    var marker;
    var icon = new LTIcon('examples/button/images/add24.gif', [24, 24], [12, 12])
    var pointDatas = [[11631376, 3999776], [11642688, 3982608], [11649198, 3996197], [11636224, 3991040]
        , [11637940, 3983135], [11646455, 3983399], [11648720, 3986983], [11648857, 3990513]

        , [11648925, 3993357], [11648375, 3995726], [11643637, 3998725], [11637181, 3998672]

        , [11630040, 3998409], [11627773, 3996883], [11627429, 3989617], [11629077, 3983028]
    ];
    var lTPoints = [];

    function toLTPoints(datas) {
        for (var p = 0; p < pointDatas.length; p++) {

            lTPoints.push(new LTPoint(pointDatas[p][0], pointDatas[p][1]));
        }
       
    }
    toLTPoints(pointDatas)
    function addMarkermap(map) {

        if (marker) {

            map.overlayManager.removeOverLaysByType("marker");

        }

        //创建参数对象 

        var option = new LTMarkerOptions();

        //设置坐标 

        option.point = new LTPoint(11636224, 3991040);
        maps.centerAndZoom(new LTPoint(11631376, 3999776), 13);
        //创建点覆盖物 

        marker = new LTMarkerOverlay(option);

        //将覆盖物添加到地图，并纳入覆盖物管理类，来进统一管理 

        map.overlayManager.addOverLay(marker);



    }

    /* 

* 添加线覆盖物到地图 

*/
    var polyLine;
    function addLTLineOverlay(map) {

        if (true) {

            //创建参数对象 

            var option = new LTLineOptions();

            //生成折线的点数组 


            var markoption = new LTMarkerOptions();
            option.points = []
            //设置坐标 
            for (var p = 0; p < lTPoints.length; p++) {

                markoption.point = lTPoints[p];
                option.points.push(markoption.point);
                //创建点覆盖物 

                marker = new LTMarkerOverlay(markoption);

                marker.setIcon(icon);

                //将覆盖物添加到地图，并纳入覆盖物管理类，来进统一管理 

                map.overlayManager.addOverLay(marker);
            }


            //根据点数组创建一条折线 

            polyLine = new LTLineOverlay(option);
            


            map.overlayManager.addOverLay(polyLine);
            map.moveToCenter(lTPoints[0], 1);

        }

    }